package com.culture.bootdemo.utils.fileutils;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.culture.bootdemo.common.basevo.ResultCode;
import com.culture.bootdemo.common.exception.BusinessException;
import com.culture.bootdemo.model.enums.FileSuffixNameEnum;
import com.google.common.base.Charsets;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: wenjl
 * @Date: 2021/6/16 16:06
 * @Description:
 */
@Component
@Slf4j
public class HuToolExcelUtil {
    public static final String EXCEL_RESPONSE_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";
    public static final String EXCEL_RESPONSE_HEADER_S1 = "Content-Disposition";
    public static final String EXCEL_RESPONSE_HEADER_S2 = "attachment;filename=";

    /**
     * 写文件到指定路径
     * 列名通过对象属性ExportField注解value获取
     *
     * @param data     数据对象列表
     * @param filePath 文件存放路径
     * @param fileName 文件名（可不带后缀）
     * @param <T>      泛型
     * @return boolean
     */
    public <T> boolean writeWithObject(List<T> data, String filePath, String fileName) {
        long start = System.currentTimeMillis();
        if (CollectionUtils.isEmpty(data) || StringUtils.isBlank(filePath) || StringUtils.isBlank(fileName)) {
            return false;
        }

        boolean success = true;

        checkMkDirs(filePath);
        fileName = checkFileName(fileName);
        filePath = filePath.concat(fileName);

        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(filePath);
        try {
            // 绑定列名
            writer = writer.setOnlyAlias(true);
            bindHeadAliasExport(writer, data.get(0));
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(data, true);
        } catch (Exception e) {
            success = false;
            e.printStackTrace();
        } finally {
            // 关闭writer，释放内存
            writer.close();
        }

        log.info("写Excel耗时:「{}」ms", System.currentTimeMillis() - start);
        return success;
    }


    /**
     * 导出为文件流
     * 列名通过对象属性ExportField注解value获取
     *
     * @param response HttpServletResponse
     * @param dataList 字符串数据列表
     * @param fileName 文件名称（可不带后缀）
     * @return boolean
     */
    public <T> void writeResponseWithObject(HttpServletResponse response, List<T> dataList, String fileName) {
        if (CollectionUtils.isEmpty(dataList) || StringUtils.isBlank(fileName)) {
            return;
        }
        fileName = checkFileName(fileName);

        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter(true);
        ServletOutputStream out = null;
        try {
            // 绑定列名
            writer = writer.setOnlyAlias(true);
            bindHeadAliasExport(writer, dataList.get(0));
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(dataList, true);
            //response为HttpServletResponse对象
            response.setContentType(EXCEL_RESPONSE_CONTENT_TYPE);
            //解决中文乱码问题
            fileName = URLEncoder.encode(new String(fileName.getBytes(Charsets.ISO_8859_1), Charsets.UTF_8), Charsets.UTF_8.name());
            //header设置文件名称
            response.setHeader(EXCEL_RESPONSE_HEADER_S1, EXCEL_RESPONSE_HEADER_S2.concat(fileName));
            //out为OutputStream，需要写出到的目标流
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.flush(out, true);
            // 关闭writer，释放内存
            writer.close();
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
        }
    }



    /**
     * 一次导出多个sheets
     * 列名通过对象属性ExportField注解value获取
     *
     * @param response
     * @param datas
     * @param fileName
     * @param sheetName
     * @param <T>
     */
    public static <T> void writeWithObject(HttpServletResponse response, List<List<? extends T>> datas, String fileName, List<String> sheetName) {
        if (CollectionUtils.isEmpty(datas) || StringUtils.isBlank(fileName) || CollectionUtils.isEmpty(sheetName) || datas.size() != sheetName.size()) {
            return;
        }
        fileName = checkFileName(fileName);

        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(fileName);
        ServletOutputStream out = null;
        try {
            for (int i = 0; i < datas.size(); i++) {
                List<? extends T> data = datas.get(i);
                if (i == 0) {
                    writer.renameSheet(sheetName.get(i));
                } else {
                    writer.setHeaderAlias(new LinkedHashMap<>());
                    writer.setSheet(sheetName.get(i));
                }
                // 绑定列名
                writer = writer.setOnlyAlias(true);
                bindHeadAliasExport(writer, data.get(0));
                // 一次性写出内容，使用默认样式，强制输出标题
                writer.write(data, true);
                response.setHeader(EXCEL_RESPONSE_HEADER_S1, EXCEL_RESPONSE_HEADER_S2.concat(fileName));

            }
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.flush(out, true);
            // 关闭writer，释放内存
            writer.close();
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
        }
    }


    /**
     * 一次写入文件 （多个sheets）
     * @param datas 数据
     * @param filePath 写入路径
     * @param fileName  写入文件名
     * @param sheetName  多个sheet
     * @param <T>
     */
    public static <T> void writeWithObject(List<List<? extends T>> datas,String filePath, String fileName, List<String> sheetName) {
        if (CollectionUtils.isEmpty(datas) || StringUtils.isBlank(fileName) || CollectionUtils.isEmpty(sheetName) || datas.size() != sheetName.size()) {
            return ;
        }
        checkMkDirs(filePath);
        fileName = checkFileName(fileName);
        fileName=filePath.concat(fileName);
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(fileName);
        try {
            for (int i = 0;i < datas.size();i++) {
                List<? extends T> data = datas.get(i);
                if (i == 0) {
                    writer.renameSheet(sheetName.get(i));
                } else {
                    writer.setSheet(sheetName.get(i));
                }
                // 绑定列名
                writer = writer.setOnlyAlias(true);
                bindHeadAliasExport(writer, data.get(0));
                // 一次性写出内容，使用默认样式，强制输出标题
                writer.write(data, true);
            }
        } catch (Exception e) {
            log.error("writeWithObject filePath:",e);
        } finally {
            writer.close();
        }
    }




    /**
     * 读取Excel文件
     * 列名通过对象属性ImportField 注解value获取
     *
     * @param fileUrl
     * @param clazz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<T> readToObject(String fileUrl, Class<T> clazz) throws Exception {
        if (StringUtils.isEmpty(fileUrl)) {
            throw new BusinessException(ResultCode.ERROR.getCode(), "文件地址为空");
        }
        return readFile(new FileInputStream(fileUrl), clazz);
    }

    private static <T> List<T> readFile(InputStream inputStream, Class<T> clazz) {
        ExcelReader reader;
        try {
            reader = ExcelUtil.getReader(inputStream);
        } catch (Exception e) {
            log.error("ExcelImport readToObject 读取数据流时异常", e);
            return null;
        }

        bindHeadAliasImport(reader, clazz);
        List<Map<String, Object>> dataList = reader.readAll();

        List<T> resultList = new ArrayList<>();
        for (Map<String, Object> map : dataList) {
            try {
                T bean = clazz.newInstance();
                BeanUtils.populate(bean, map);
                resultList.add(bean);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return resultList;
    }

    /**
     * 检查文件后缀，没有则补充，并支持中文文件名
     */
    @SneakyThrows
    private static String checkFileName(String fileName) {
        if (!fileName.contains(FileSuffixNameEnum.xlsx.getName())) {
            fileName = fileName.concat(FileSuffixNameEnum.xlsx.getName());
        }
        fileName = new String(fileName.getBytes(), Charsets.ISO_8859_1);
        return fileName;
    }

    /**
     * 检查目录文件目录是否创建，没创建，则尝试创建
     */
    private static void checkMkDirs(String filePath) {
        File dirFile = new File(filePath);
        if (!dirFile.isDirectory()) {
            boolean mkdirs = dirFile.mkdirs();
            log.info("创建目录是否成功:{}", mkdirs);
        }
    }

    /**
     * 把实例类上的注解value绑定到Excel表头
     */
    @SuppressWarnings("unchecked")
    private static <T> void bindHeadAliasExport(ExcelWriter writer, T t) {
        Class<T> clazz = (Class<T>) t.getClass();
        if (null != clazz) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                ExportField exportField = field.getAnnotation(ExportField.class);
                if (exportField != null) {
                    writer.addHeaderAlias(field.getName(), exportField.value());
                }
            }
        }
    }


    /**
     * 把实例类上的注解value绑定到Excel表头
     */
    private static <T> void bindHeadAliasImport(ExcelReader reader, Class<T> clazz) {
        if (null != clazz) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                ImportField importField = field.getAnnotation(ImportField.class);
                if (importField != null) {
                    reader.addHeaderAlias(importField.value(), field.getName());
                }
            }
        }
    }

}
